package cc.monggo.third.impl;

import java.util.HashMap;

import org.apache.commons.lang.StringUtils;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
import cc.monggo.third.RenrenService;
import cc.monggo.third.client.ThirdAuthClient;
import cc.monggo.third.model.RenrenUser;

public class RenrenServiceImpl implements RenrenService {

	@Override
	public RenrenUser getAccessToken(HashMap<String, String> params) {
		RenrenUser renrenUser = new RenrenUser();
		String body = ThirdAuthClient.postSSL(params);
		
		try{
			if(!StringUtils.isBlank(body)){
				JSONObject jsonO = new JSONObject(body);

				renrenUser.setAccessToken(jsonO.getString("access_token"));
				renrenUser.setExpiresIn(jsonO.getString("expires_in"));
				
				JSONObject userO = (JSONObject)jsonO.get("user");
				renrenUser.setId(userO.getString("id"));
				renrenUser.setName(userO.getString("name"));
				
				JSONArray avatarArr = (JSONArray)userO.get("avatar");
				for(int i=0;i<avatarArr.length();i++){
					JSONObject o = avatarArr.getJSONObject(i);
					if(o.getString("type").equalsIgnoreCase("tiny")){
						renrenUser.setImageUrl_tiny(o.getString("url"));
					}else if(o.getString("type").equalsIgnoreCase("main")){
						renrenUser.setImageUrl_main(o.getString("url"));
					}else if(o.getString("type").equalsIgnoreCase("large")){
						renrenUser.setImageUrl_large(o.getString("url"));
					}
				}			
				return renrenUser;
			}
			
		}catch(JSONException e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void main(String args[]){
		/*String s = "{'expires_in':'2595208','user':{'id':'458916009','avatar':[{'type':'avatar','url':'13dfsdfsd2'},{'type':'avatar','url':'13242'}]}}";
		try{
			if(!StringUtils.isBlank(s)){
				JSONObject jsonO = new JSONObject(s);				
				JSONObject userO = (JSONObject)jsonO.get("user");			
				JSONArray avatarArr = (JSONArray)userO.get("avatar");
				//JSONArray imgArr = avatarArr.getJSONArray(0);
				for(int i=0;i<avatarArr.length();i++){
					JSONObject o = avatarArr.getJSONObject(i);
					System.out.println(o);
				}
			}			
		}catch(JSONException e){
			e.printStackTrace();
		}*/
		
		//String = "http:\/\/hdn.xnimg.cn\/photos\/hdn521\/20120509\/0945\/h_head_sUZL_259f000064032f76.jpg"

	}

}

